<template>
  <view class="flex flex-col">
    <S1Header title="赊欠录入" :on-back="onBack" />

    <view class="border-f5f5f5 mt-20rpx flex justify-between border-b bg-white">
      <view
        class="tab-item"
        :class="{ 'tab-active': activeTab === 0 }"
        @click="changeTab(0)"
      >
        支出录入
      </view>
      <view
        class="tab-item"
        :class="{ 'tab-active': activeTab === 1 }"
        @click="changeTab(1)"
      >
        收入录入
      </view>
    </view>

    <view class="main-container">
      <view class="bg-[rgba(242,247,255,1)] p-20rpx">
        <!-- 金额输入 -->
        <view class="form-block">
          <text class="form-label">
            {{ activeTab === 0 ? "支出" : "收入" }}金额
          </text>
          <view class="input-group">
            <input
              v-model="amount"
              class="h-60rpx flex-1 text-32rpx"
              :placeholder="`请输入${activeTab === 0 ? '支出' : '收入'}金额`"
              type="number"
            >
            <div class="input-unit">
              元
            </div>
          </view>
        </view>

        <!-- 支付方式 -->
        <view class="payment-methods-container">
          <view
            v-for="method in paymentMethods"
            :key="method.id"
            class="payment-method-item"
            :class="{ 'payment-method-active': selectedMethod === method.id }"
            @click="selectPaymentMethod(method.id)"
          >
            <view
              class="mb-8rpx text-2xl" :class="[
                method.icon,
                selectedMethod === method.id ? 'text-white' : 'text-gray-500',
              ]"
            />
            <text
              class="text-26rpx"
              :class="{
                'text-white': selectedMethod === method.id,
                'text-gray-800': selectedMethod !== method.id,
              }"
            >
              {{ method.name }}
            </text>
          </view>
        </view>

        <!-- 费用项目 -->
        <view class="form-block">
          <text class="form-label">
            {{ activeTab === 0 ? "支出" : "收入" }}项目
          </text>
          <view class="input-group" @click="toggleImportPopup('expense')">
            <input
              class="h-60rpx flex-1 text-32rpx"
              :placeholder="`请选择${activeTab === 0 ? '支出' : '收入'}项目`"
              disabled
              :value="selectedExpenseItem?.name || ''"
            >
            <div class="input-action-button">
              导入
            </div>
          </view>
        </view>

        <!-- 关联批次 -->
        <view class="form-block">
          <text class="form-label">
            关联批次
          </text>
          <view class="input-group" @click="toggleImportPopup('batch')">
            <input
              class="h-60rpx flex-1 text-32rpx"
              placeholder="请选择关联批次"
              disabled
              :value="selectedBatch?.name || ''"
            >
            <div class="input-action-button">
              关联
            </div>
          </view>
        </view>

        <!-- 备注信息 -->
        <view class="form-block">
          <text class="form-label">
            备注信息
          </text>
          <view class="input-group">
            <input
              v-model="notes"
              class="flex-1 p-2px p-8px text-32rpx"
              placeholder="请输入备注信息"
            >
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="mt-40rpx flex justify-center">
          <view
            class="h-90rpx w-100% flex items-center justify-center rounded-10rpx bg-[#43CF7C]"
            @click="handleSubmit"
          >
            <text class="text-34rpx text-white font-bold">
              提交
            </text>
          </view>
        </view>
      </view>
    </view>

    <SearchFilterPopup
      :show="showImportPopup"
      :title="popupTitle"
      :type="activeTab === 0 ? 1 : 2"
      input-placeholder="搜索名称"
      :list="importItems"
      @update:show="showImportPopup = $event"
      @item-select="onItemSelect"
      @search="handleSearch"
    />
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import {
  addZhichuData,
  getAllFeiyongxiangData,
  getAllPiciData,
} from '@/api/statistics';
import * as S1Header from '@/components/S1Header.vue';
import * as SearchFilterPopup from '@/components/SearchFilterPopup.vue';

interface PaymentMethod {
  id: string;
  name: string;
  icon: string;
}

// 响应式数据
const activeTab = ref(0);
const amount = ref('');
const showImportPopup = ref(false);
const selectedMethod = ref('cash');
const selectedExpenseItem = ref<any>(null);
const selectedBatch = ref<any>(null);
const notes = ref('');
const importItems = ref<any[]>([]);
const popupType = ref<'expense' | 'batch'>('expense');
const isLoading = ref(false);

// 计算属性
const popupTitle = computed(() =>
  popupType.value === 'expense'
    ? `${activeTab.value === 0 ? '支出' : '收入'}项目搜索`
    : '批次搜索',
);

const paymentMethods = ref<PaymentMethod[]>([
  { id: 'cash', name: '现金', icon: 'i-mdi-cash-multiple' },
  { id: 'wechat', name: '微信', icon: 'i-mdi-wechat' },
  { id: 'alipay', name: '支付宝', icon: 'i-mdi-alpha-a-circle' },
  { id: 'unionpay', name: '银联', icon: 'i-mdi-credit-card' },
  { id: 'other', name: '其他', icon: 'i-mdi-dots-horizontal' },
]);

// 方法
const onBack = () => {
  uni.navigateBack();
};

const handleSubmit = async () => {
  if (isLoading.value) return;

  if (!amount.value || !selectedExpenseItem.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none',
    });
    return;
  }

  const payTypeMap: Record<string, number> = {
    cash: 1,
    wechat: 2,
    alipay: 3,
    unionpay: 4,
    other: 5,
  };

  try {
    isLoading.value = true;
    const res = await addZhichuData({
      money: amount.value,
      name: selectedExpenseItem.value.name,
      name_id: selectedExpenseItem.value.id,
      notes: notes.value,
      pay_type: payTypeMap[selectedMethod.value],
      pici_id: selectedBatch.value?.id || 0,
      type: activeTab.value === 0 ? 1 : 2,
    });

    if (res.code === 200) {
      uni.showToast({
        title: '提交成功',
        icon: 'success',
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  }
  catch (error) {
    uni.showToast({
      title: '提交失败',
      icon: 'error',
    });
  }
  finally {
    isLoading.value = false;
  }
};

const changeTab = (tabIndex: number) => {
  activeTab.value = tabIndex;
  // 清空选择的项目，因为不同的Tab有不同的项目列表
  selectedExpenseItem.value = null;
};

const selectPaymentMethod = (methodId: string) => {
  selectedMethod.value = methodId;
};

const toggleImportPopup = async (type: 'expense' | 'batch') => {
  if (isLoading.value) return;

  popupType.value = type;
  isLoading.value = true;

  try {
    if (type === 'expense') {
      const res = await getAllFeiyongxiangData({
        type: activeTab.value === 0 ? 1 : 2,
        keywords: '',
      });
      if (res.code === 200) {
        importItems.value = res.data.map((item: any) => ({
          name: item.name,
          id: item.id,
          phone: '', // 确保搜索过滤能正常工作
        }));
      }
    }
    else {
      const res = await getAllPiciData({
        status: 1,
        keywords: '',
      });
      if (res.code === 200) {
        importItems.value = res.data.map((item: any) => ({
          name: `${item.huozhu_name} - ${item.pici}`,
          id: item.id,
          phone: '', // 确保搜索过滤能正常工作
        }));
      }
    }
    showImportPopup.value = true;
  }
  catch (error) {
    uni.showToast({
      title: '获取数据失败',
      icon: 'error',
    });
  }
  finally {
    isLoading.value = false;
  }
};

const onItemSelect = (item: any) => {
  if (popupType.value === 'expense') {
    selectedExpenseItem.value = item;
  }
  else {
    selectedBatch.value = item;
  }
  showImportPopup.value = false;
};

const handleSearch = async (keyword: string) => {
  if (isLoading.value) return;
  isLoading.value = true;

  try {
    if (popupType.value === 'expense') {
      const res = await getAllFeiyongxiangData({
        type: activeTab.value === 0 ? 1 : 2,
        keywords: keyword,
      });
      if (res.code === 200) {
        importItems.value = res.data.map((item: any) => ({
          name: item.name,
          id: item.id,
          phone: '',
        }));
      }
    }
    else {
      const res = await getAllPiciData({
        status: 1,
        keywords: keyword,
      });
      if (res.code === 200) {
        importItems.value = res.data.map((item: any) => ({
          name: `${item.huozhu_name} - ${item.pici}`,
          id: item.id,
          phone: '',
        }));
      }
    }
  }
  catch (error) {
    uni.showToast({
      title: '搜索失败',
      icon: 'error',
    });
  }
  finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.tab-item {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #666;
  padding: 20rpx;
  border-radius: 5rpx;
  transition: all 0.3s;
}

.tab-active {
  color: white;
  background-color: #43cf7c;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-block {
  margin-bottom: 20rpx;
  border-bottom: 1px solid #eee;
  padding: 20rpx;
  background-color: white;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: black;
  font-size: 17px;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.input-group {
  display: flex;
  align-items: center;
  background-color: rgba(242, 247, 255, 1);
  padding-left: 12px;
  border-radius: 5px;
}

.input-unit,
.input-action-button {
  border-radius: 0 7.43px 7.43px 0;
  background-color: rgba(67, 207, 124, 1);
  border: 1px solid rgba(229, 229, 229, 1);
  color: white;
  font-size: 32rpx;
  width: 120rpx;
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  font-weight: bold;
}

.payment-methods-container {
  display: flex;
  padding: 20rpx;
  background-color: white;
  margin-bottom: 20rpx;
  justify-content: space-around;
}

.payment-method-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15rpx 25rpx;
  border-radius: 16rpx;
}

.payment-method-active {
  background-color: #43cf7c;
  color: white;
}
</style>
